import Logger from "../../../utils/logger";

export default function createEdge(metadata, graph) {
  Logger.log('创建边...')
  const shape = metadata.sourceCell.shape
  // console.log(shape)
  if (EdgeRule[shape]) {
    return EdgeRule[shape](metadata, graph)
  }

  Logger.log('创建通用边...')
  return graph.addEdge({
    shape: 'common-edge',
  })
}

const EdgeRule = {
  condition(metadata, graph) {
    Logger.log('根据【条件】节点规则创建边...')
    const {sourceCell} = metadata
    const sourceEdges = graph.getOutgoingEdges(sourceCell) || []

    const trueEdge = sourceEdges.find(edge => edge.getData().labelValue === true)
    const falseEdge = sourceEdges.find(edge => {
      const _edgeData = edge.getData()
      return _edgeData.labelValue === false && _edgeData.labelValue !== undefined
    })

    const trueEdgeModel = {
      shape: 'condition-edge',
      label: '是',
      data: {
        dialogData: {
          parentPoint: 0
        },
        labelValue: true,
      }
    }

    const falseEdgeModel = {
      shape: 'condition-edge',
      label: '否',
      data: {
        dialogData: {
          parentPoint: 1
        },
        labelValue: false,
      },
    }

    let edge
    if (trueEdge && falseEdge) {
      Logger.error('已存在 "是" 边 且 已存在 "否" 边 ')
      edge = graph.addEdge({
        shape: 'common-edge',
        attrs: {
          fill: '#FF0000'
        }
      })
    } else if (!!trueEdge) {
      edge = graph.addEdge(falseEdgeModel)
    } else if (!!falseEdge) {
      edge = graph.addEdge(trueEdgeModel)
    } else {
      edge = graph.addEdge(trueEdgeModel)
    }

    return edge
  },

  switcherConcurrent({cell, dialogData}, graph) {
    Logger.log('根据【并行分支】节点规则创建边...')
    return graph.addEdge({
      shape: 'switcherConcurrent-edge',
    })
  },

  switcherCondition(e, graph) {
    const outgoingEdges = graph.getOutgoingEdges(e.sourceCell) || []
    const parentPoints = outgoingEdges.map(edge => edge.getData().dialogData.parentPoint)
    parentPoints.sort((a, b)=>a-b)

    let parentPoint = outgoingEdges.length + 1
    for (let i = 0; i<parentPoints.length; i++) {
      const currentValue = parentPoints[i]
      const previousValue = parentPoints[i - 1]
      if (currentValue === 1) {
        continue
      }

      if (previousValue === undefined) {
        parentPoint = 1
        break
      }

      if (previousValue + 1 !== currentValue) {
        parentPoint = previousValue + 1
        break
      }
    }

    return graph.addEdge({
      shape: 'switcherCondition-edge',
      label: parentPoint + '',
      data: {
        dialogData: {
          parentPoint,
        }
      },
    })
  },
}
